<template>
  <a-modal
      width="560px"
      :visible="visible"
      title="公海规则"
      @cancel="onClose"
      @ok="onCommit"
      ok-text="保存"
  >
    <a-form
        style="max-height: 600px; overflow: auto; padding-right: 4px"
    >
      <div class="title-box">
        <div class="title-left"></div>
        <div class="title">线索公海</div>
      </div>
      <a-form-item label="公海领取：">
        <a-radio-group v-model:value="receive_type" name="radioGroup">
          <a-radio :value="1">仅管理员分配</a-radio>
          <a-radio :value="2">成员可领取+管理员分配</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="回收规则">
        <a-radio-group v-model:value="recovery_type" name="radioGroup">
          <a-radio :value="1">自动回收</a-radio>
          <a-radio :value="2">手动回收</a-radio>
        </a-radio-group>
      </a-form-item>

      <template v-if="recovery_type == 1">
        <div
            class="rule-box"
            v-for="(item, index) in recovery_rule"
            :key="index"
        >
          <div style="width: 60px; height: 32px; line-height: 32px">
            规则{{ index + 1 }}：
          </div>
          <div style="flex: 1">
            <div class="rule-item">
              <span>在</span>
              <a-select
                  v-model:value="item.status"
                  style="width: 90px; margin: 0 4px; font-size: 12px"
                  size="small"
                  :options="statusOptions"
                  @change="
                  (val, option) => {
                    changeStatus(val, option, item);
                  }
                "
              ></a-select
              >
              状态下
              <a-input-number
                  placeHolder="请输入"
                  class="rule-input"
                  size="small"
                  :min="0"
                  :precision="0"
                  v-model:value="item.back_day"
              />
              天未添加跟进记录，自动回收至公海
            </div>
            <div class="rule-item">
              <span>在回收</span
              >
              <a-input-number
                  placeHolder="请输入"
                  class="rule-input"
                  size="small"
                  :precision="0"
                  :min="0"
                  v-model:value="item.recovery_day"
              />
              天前提醒员工
            </div>
            <div class="rule-item">
              <span> 若首次推送提醒后，依然没有添加跟进记录，之后每隔</span
              >
              <a-input-number
                  placeHolder="请输入"
                  class="rule-input"
                  size="small"
                  :precision="0"
                  :min="0"
                  v-model:value="item.remind_hour"
              />
              小时再次提醒
            </div>
            <div class="rule-item-sub">
              <span> (填写0，代表不推送提醒通知员工) </span>
            </div>
          </div>
          <CloseCircleOutlined
              class="close-icon"
              v-if="recovery_rule.length > 1"
              @click.stop="deleteRule(index)"
          />
        </div>
      </template>

      <a-form-item v-if="recovery_type == 1">
        <a-button
            type="primary"
            ghost
            @click="addRecoverRule"
            :disabled="!canAddRule"
        >添加规则
          <a-tooltip>
            <template #title>根据实际的业务量推送消息时间会有些许误差</template>
            <QuestionCircleOutlined class="ml-5"/>
          </a-tooltip>
        </a-button>
      </a-form-item>

      <a-form-item label="员工捡回">
        <div class="rule-item">
          <span> 自回收至公海池</span
          >
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :precision="0"
              :min="0"
              v-model:value="pickup_day"
          />
          天后可重新捡回（填0则可当天捡回。）
        </div>
        <div class="rule-item-sub">
          <span>
            在某员工手上丢失的线索，回收至公海池，只可在规定的时间后才可重新领取
          </span>
        </div>
      </a-form-item>

      <a-form-item label="领取资格">
        <div class="rule-item">
          <a-checkbox
              style="margin-right: 5px"
              :checked="receive_rule.is_use == 1"
              @change="receive_rule.is_use = receive_rule.is_use == 1 ? 0 : 1"
          ></a-checkbox>
          <span> 从公海领取的总线索中有</span
          >
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :min="0"
              :precision="0"
              v-model:value="receive_rule.num"
              :disabled="receive_rule.is_use == 0"
          />
          个未跟进则不允许再领取公海线索资源
        </div>
      </a-form-item>
      <a-form-item label="领取上限">
        <div class="rule-item">
          <a-checkbox
              style="margin-right: 5px"
              :checked="receive_limit.is_use == 1"
              @change="receive_limit.is_use = receive_limit.is_use == 1 ? 0 : 1"
          ></a-checkbox>
          <span>每个员工可领取线索共</span
          >
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :min="0"
              :precision="0"
              :disabled="receive_limit.is_use == 0"
              v-model:value="receive_limit.num"
          />
          个
        </div>
        <div class="rule-item-sub">
          <span>
            当员工领取的线索数，又退回到公海时或转为已成交时，则恢复员工
            的可领取数
          </span>
        </div>
      </a-form-item>
      <a-form-item label="每日上限">
        <div class="rule-item">
          <a-checkbox
              style="margin-right: 5px"
              :checked="daily_limit.is_use == 1"
              @change="daily_limit.is_use = daily_limit.is_use == 1 ? 0 : 1"
          ></a-checkbox>
          <span>每个员工单日可领取线索</span
          >
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :precision="0"
              :min="0"
              :disabled="daily_limit.is_use == 0"
              v-model:value="daily_limit.num"
          />
          个
        </div>
        <div class="rule-item-sub">
          <span>
            同一线索在当日领取，又在当天被退回时，则恢复员工的单日可领取数
          </span>
        </div>
      </a-form-item>
      <a-form-item label="连续领取">
        <div class="rule-item">
          <a-checkbox
              style="margin-right: 5px"
              :checked="receive_next.is_use == 1"
              @change="receive_next.is_use = receive_next.is_use == 1 ? 0 : 1"
          ></a-checkbox>
          <span>员工连续领取线索时间间隔至少</span
          >
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :precision="0"
              :min="0"
              :max="23"
              :disabled="receive_next.is_use == 0"
              v-model:value="receive_next.hour"
          />
          时
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :precision="0"
              :min="0"
              :max="59"
              :disabled="receive_next.is_use == 0"
              v-model:value="receive_next.minute"
          />
          分
        </div>
      </a-form-item>
      <div class="title-box">
        <div class="title-left"></div>
        <div class="title">渠道线索保护期</div>
      </div>
      <a-form-item label="线索保护">
        <div class="rule-item">
          <span>当渠道提交的线索</span
          >
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :precision="0"
              :min="0"
              v-model:value="protect_day"
          />
          天后未成交，则其他渠道则可再次提交此线索,并且提前
          <a-input-number
              placeHolder="请输入"
              class="rule-input"
              size="small"
              :precision="0"
              :min="0"
              v-model:value="protect_remind_day"
          />
          天提醒渠道
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import {ref, reactive, toRefs, watch, computed} from "vue";
import request from "../../../../common/utils/request";
import {message} from "ant-design-vue";
import store from "@/store";
import _ from "lodash";
import {
  CloseCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";

export default {
  name: "ClueSeaRule",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: {CloseCircleOutlined, QuestionCircleOutlined},
  setup(props, context) {
    const state = reactive({
      statusList: [],
    });

    const formData = reactive({
      receive_type: 1, //1=仅管理员分配;2=成员可领取+管理员分配',
      recovery_type: 1, //回收规则;1=自动回收2=手动回收',
      pickup_day: 7, //可拾回限定天数
      recovery_rule: [],
      receive_rule: {is_use: 0, num: ""}, //领取资格规则
      receive_limit: {is_use: 0, num: ""}, //领取上限规则
      daily_limit: {is_use: 0, num: ""}, //每日上限规则
      receive_next: {is_use: 0, hour: "", minute: ""}, //连续领取规则
      //渠道线索保护期
      protect_day: 30,
      protect_remind_day: 10


    });

    const statusOptions = computed(() => {
      state.statusList.forEach((v) => {
        let index = (formData.recovery_rule || []).findIndex(
            (item) => item.status == v.value
        );
        if (index !== -1) {
          v.disabled = true;
        } else {
          v.disabled = false;
        }
      });
      return _.cloneDeep(state.statusList);
    });

    const canAddRule = computed(() => {
      return !(statusOptions.value || []).every((v) => v.disabled);
    });

    const changeStatus = (val, option, item) => {
      item.status_txt = option?.label || "";
    };

    //回收规则
    const addRecoverRule = () => {
      formData.recovery_rule.push({
        status: undefined,
        status_txt: "",
        back_day: 7,
        recovery_day: 1,
        remind_hour: 0,
      });
    };

    const getStatusList = () => {
      request
          .get("/org", "/business/clueStatus/clueStatusList ")
          .then((res) => {
            console.log(res);
            let list = (res?.list || []).filter((v) => v.status !== 33); // 33是转意向客户
            state.statusList = list.map((v) => {
              return {
                label: v.name,
                value: v.status,
              };
            });
          });
    };

    const deleteRule = (index) => {
      formData.recovery_rule.splice(index, 1);
    };

    const setModelRef = (info) => {
      console.log(info);
      for (let key in formData) {
        formData[key] = info[key];
      }
    };

    // 获取公海规则
    const getPoolRules = () => {
      request.get("/org", "/business/clue/getCluePool", {}).then((res) => {
        setModelRef(res.list);
      });
    };

    const init = () => {
      getStatusList();
      getPoolRules();
    };

    const reset = () => {
      state.statusList = [];
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            reset();
          }
        }
    );

    const onClose = () => {
      context.emit("handleClose");
    };
    const onCommit = (e) => {
      const param = _.cloneDeep(formData);
      param.recovery_rule = param.recovery_rule.filter(
          (v) => v.status || v.status == 0
      );
      if (param.recovery_type == 1 && !param.recovery_rule.length) {
        message.warning("至少需要一条有效自动回收规则");
        return;
      }
      request.post("/org", "/business/clue/setCluePool", param).then((res) => {
        message.success("设置成功");
        context.emit("commit");
      });
    };
    return {
      ...toRefs(formData),
      ...toRefs(state),
      statusOptions,
      canAddRule,
      onClose,
      onCommit,
      addRecoverRule,
      changeStatus,
      deleteRule,
    };
  },
};
</script>

<style lang="less" scoped>
.rule-box {
  background-color: #f2f2f2;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  padding: 4px 16px 4px 6px;
  margin-bottom: 10px;
  position: relative;

  .close-icon {
    cursor: pointer;
    position: absolute;
    right: 2px;
    top: 4px;
  }
}

.rule-item {
  font-size: 13px;
  //height: 32px;
  line-height: 32px;
}

.rule-item-sub {
  color: #666;
  font-size: 11px;
}

.rule-input {
  width: 50px;
  margin: 0 4px;
}

.title-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 40px;

  .title-left {
    height: 12px;
    width: 4px;
    border-radius: 2px;
    background-color: #2681f3;
  }

  .title {
    margin-left: 4px;
    color: #333;
  }
}
</style>
